package com.xli.sso.security.filter;

import cn.hutool.core.util.StrUtil;
import com.xli.sso.security.exception.CustomerAuthenionException;
import com.xli.sso.security.handler.LoginFailureHandler;
import com.xli.sso.security.identity.LoginUser;
import com.xli.sso.security.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class CheckTokenFilter extends OncePerRequestFilter {

    //@Value("${login.url}")
    private final String loginUrl = "/xli-web/rest/login";

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求的url(读取配置文件的url)
        String url = request.getRequestURI();
        if (StrUtil.contains(request.getServletPath(), "swagger")) {
            filterChain.doFilter(request, response);
        } else if (StrUtil.equals(url, loginUrl)) {
            // 是登录请求放行
            filterChain.doFilter(request, response);
        } else {
            try {
                //token验证（如果不是登录请求 验证toekn）
                if (!url.equals(loginUrl)) {
                    validateToken(request);
                }
                filterChain.doFilter(request, response);
            } catch (AuthenticationException e) {
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
    }

    //token验证
    private void validateToken(HttpServletRequest request) {
        LoginUser loginUser = JwtUtil.getLoginUser(request);
        if (loginUser == null) {
            throw new CustomerAuthenionException("token验证失败!");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        //设置到spring security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
